package cn.wolfcode.luowowo.website.web.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 让springmvc直接将当前登录用户注入到请求映射方法的参数中去
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //该解析器支持解析哪一种类型的参数: UserInfo
    //如果返回false: 不支持解析,不执行resolveArgument方法, true: 表示支持解析, 马上执行resolveArgument方法
    public boolean supportsParameter(MethodParameter methodParameter) {
        return  methodParameter.hasParameterAnnotation(UserParam.class)
                && methodParameter.getParameterType() == UserInfo.class;
    }

    //将上面supportsParameter 返回true时执行
    //将上面支持的类型,装换为实例对象, 注入请求映射方法的形参上
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String token = CookieUtil.getCookie(request, response);
        UserInfo user = userInfoRedisService.getUserByToken(token);

        return user;
    }
}
